package org.visionlibrary.image.filters.rescaling;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class GrayScale extends AbstractFilter {
	public TiledImage applyFilter(TiledImage src, TiledImage dest)
			throws IllegalArgumentException {
		if (null == src)
			throw new NullPointerException("Source image is null.");
		
		if (dest != null)
			throw new IllegalArgumentException(
					"This only works with construction: dest = filter.applyFilter( src, null );");

		dest = (new ImageFactory()).createCompatibleGrayScaleImage(src);

		for (int y = 0; y < src.getHeight(); y++)
			for (int x = 0; x < src.getWidth(); x++) {
				int sum = 0;
				for (int band = 0; band < src.getNumBands(); band++)
					sum += src.getSample(x, y, band);

				dest.setSample(x, y, 0, sum / src.getNumBands());
			}

		return dest;
	}

}
